#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
改进的实时语音转文字程序
支持在线（Google）和离线（Sphinx）模式
"""

import time

import speech_recognition as sr


def online_speech_to_text():
    """在线语音识别（Google，支持中文）"""
    r = sr.Recognizer()

    with sr.Microphone() as source:
        print("=== 在线语音识别模式 ===")
        print("使用Google语音识别服务（支持中文）")
        print("正在调整环境噪声...")
        r.adjust_for_ambient_noise(source, duration=2)
        print("开始说话吧！")

        while True:
            try:
                print("正在听...")
                audio = r.listen(source, timeout=3, phrase_time_limit=5)

                print("正在识别...")
                text = r.recognize_google(audio, language="zh-CN")
                print(f"你说: {text}")

            except sr.WaitTimeoutError:
                print("等待中...")
            except sr.UnknownValueError:
                print("没听清楚，请再说一遍")
            except sr.RequestError as e:
                print(f"网络连接有问题: {e}")
            except KeyboardInterrupt:
                print("\n程序退出")
                break


def offline_speech_to_text():
    """离线语音识别（Sphinx，仅支持英文）"""
    r = sr.Recognizer()

    with sr.Microphone() as source:
        print("=== 离线语音识别模式 ===")
        print("使用Sphinx本地识别（仅支持英文）")
        print("正在调整环境噪声...")
        r.adjust_for_ambient_noise(source, duration=2)
        print("开始说话吧！(Speak in English)")

        while True:
            try:
                print("正在听...")
                audio = r.listen(source, timeout=3, phrase_time_limit=5)

                print("正在识别...")
                text = r.recognize_sphinx(audio)
                print(f"你说: {text}")

            except sr.WaitTimeoutError:
                print("等待中...")
            except sr.UnknownValueError:
                print("没听清楚，请再说一遍")
            except Exception as e:
                print(f"识别出错: {e}")
            except KeyboardInterrupt:
                print("\n程序退出")
                break


def test_microphone():
    """测试麦克风功能"""
    print("=== 麦克风测试 ===")

    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("正在调整环境噪声...")
        r.adjust_for_ambient_noise(source, duration=2)
        print("请说一句话进行测试（5秒内）...")

        try:
            audio = r.listen(source, timeout=5, phrase_time_limit=5)
            print(f"音频录制成功！长度: {len(audio.frame_data)} 字节")
            return True
        except sr.WaitTimeoutError:
            print("等待超时，没有检测到声音")
            return False
        except Exception as e:
            print(f"测试失败: {e}")
            return False


def main():
    print("语音转文字程序")
    print("1. 在线模式（Google，支持中文，需要网络）")
    print("2. 离线模式（Sphinx，仅支持英文）")
    print("3. 测试麦克风")

    choice = input("请选择模式 (1/2/3): ").strip()

    if choice == "1":
        online_speech_to_text()
    elif choice == "2":
        offline_speech_to_text()
    elif choice == "3":
        success = test_microphone()
        if success:
            print("✅ 麦克风测试成功！")
        else:
            print("❌ 麦克风测试失败")
    else:
        print("无效选择，使用在线模式")
        online_speech_to_text()


if __name__ == "__main__":
    main()
